#include "Graphics2D.h"

//=====INITIALIZE
void Graphics2D::LoadTexture(IDirect3DDevice9* Device,int Element, char* Address)
{
	D3DXCreateTextureFromFileEx										
		(Device, Address, 0, 0, 0, 0,
		D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT,
		D3DX_DEFAULT, D3DCOLOR_XRGB(0, 0 ,255),
		&mdImageInfo[Element], 0, &mdTextures[Element]);

	D3DSURFACE_DESC Dimensions;
	mdTextures[Element]->GetLevelDesc(0,&Dimensions);
	float X = Dimensions.Width  * 0.5f;
	float Y = Dimensions.Height * 0.5f;
	mdTexCenter[Element] = D3DXVECTOR3(X,Y,0.0f);
}
bool Graphics2D::InitTextures(IDirect3DDevice9* Device)
{

	for(int i = 0; i < TEX_SIZE; i++)
		m_cszTexNames[i] = "Textures//Texture1.jpg";

	m_cszTexNames[TEX_BUTTON]  = "Textures//Button.png";
	m_cszTexNames[TEX_MENUPANE]= "Textures//MenuPanel.png";
	m_cszTexNames[TEX_SPLASH]  = "Textures//Splash.png";

	for(int i = 0; i < TEX_SIZE; i++)
		if(m_cszTexNames[i] != NULL){
			LoadTexture(Device,i,m_cszTexNames[i]);
			if(mdTextures[i] == NULL)		// if any file was unable to be loaded, stop the program
				return false;
		}
		return true;
};
void Graphics2D::InitFont(IDirect3DDevice9* Device)
{
	D3DXCreateFont(Device, 18, 0, 0, 0, false,				
		DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY,
		DEFAULT_PITCH | FF_DONTCARE, TEXT("Times New Roman"),
		&FontDevice);	
}
void Graphics2D::Initialize	 (IDirect3DDevice9* Device)
{
	D3DXCreateSprite(Device, &Sprite);								//Create Sprite object
	InitTextures(Device);
	InitFont(Device);

};
//=====RENDER
void Graphics2D::RenderFont(BaseSprite* S)
{
	string Text = S->GetText();

	if(S->getObjID()==TEX_BUTTON)
		FontDevice->DrawTextA(NULL,Text.c_str(),					
		Text.size(),&S->GetRect(),								
		DT_CENTER |DT_SINGLELINE|DT_VCENTER|DT_NOCLIP,
		D3DCOLOR_ARGB(255, 255, 255, 255));						

	if(S->getObjID()==TEX_MENUPANE || S->getObjID()== TEX_SPLASH)
		FontDevice->DrawTextA(NULL,Text.c_str(),				
		Text.size(),&S->GetRect(),								
		DT_CENTER |DT_TOP|DT_NOCLIP,
		D3DCOLOR_ARGB(255, 255, 255, 255));				
}
void Graphics2D::Render2D(SpriteList& OList, int CurrentState)
{	
	Sprite->Begin(D3DXSPRITE_ALPHABLEND);	

	for(unsigned int i(0); i < OList.size(); i++){
		if(OList[i]->GetShowState() == CurrentState){

			int TextureInd = OList[i]->getObjID();				//Grab the texture index of this object

			Sprite->SetTransform(&OList[i]->getTransform());		//Move the sprite into place

			Sprite->Draw(mdTextures[TextureInd],NULL,			
				&mdTexCenter[TextureInd],NULL,
				OList[i]->getColor()); 
		}
	}
	Sprite->End();	

	for(unsigned int i(0); i < OList.size(); i++){
		if(OList[i]->GetShowState() == CurrentState){
			RenderFont(OList[i]);
		}
	}
};
//=====ACESSORS
DXTEXTURE2 Graphics2D::GetTexture(int ID)
{
	return mdTextures[ID];
}